package com.nb.sse.controller;


import cn.hutool.json.JSONUtil;
import com.nb.sse.auth.LoginUser;
import com.nb.sse.auth.UserContextHolder;
import com.nb.sse.entity.Message;
import com.nb.sse.entity.SysNotice;
import com.nb.sse.entity.SysUser;
import com.nb.sse.service.ISysNoticeService;
import com.nb.sse.service.MessageService;
import com.nb.sse.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author
 * @since 2020-10-28
 */
@Slf4j
@RestController
@RequestMapping("/sse")
public class SSEController {

    // 使用线程池来管理SSE的发送，避免阻塞主线程
    private ExecutorService executor = Executors.newFixedThreadPool(4);

    @Autowired
    MessageService messageService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter events() {
        log.info(">>>>>>>>>>>.. 进入到events <<<<<<<<<<<<<<");
        // Long.MAX_VALUE是超时时间，这里设置为最大以避免自动超时
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        LoginUser user = UserContextHolder.getUser();
        Integer userId = user.getUserId();

        messageService.addEmitter(userId, emitter);
        emitter.onTimeout(() -> messageService.removeEmitter(userId));
        emitter.onCompletion(() -> messageService.removeEmitter(userId));

        return emitter;
    }





}

